// pages/user/cert/certDetail.js
var app = getApp()
var util = require('../../../utils/util.js')
var api = require('../../../config/api.js');


Page({

  /**
   * 页面的初始数据
   */
  data: {
    urla:'',
    id:'',//用户id
    type:'',//车型，方便查合同链接
    stu:{},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // console.log(options);
    var id = options.id  //获取ID
    var type = options.type//获取车型
    this.setData({
      id:id,
      type:type
    })
    //this.loadStuDetail()
    this.getHtUrl();
  },
  //复制网址
  copyText: function (e) {
    console.log(e)
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function (res) {
        wx.getClipboardData({
          success: function (res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },
  //取合同链接
  getHtUrl(){
    var that = this;
    util.request(api.getHtUrl,{userid:this.data.id,type:this.data.type}).then(function(res){
      console.log(res)
      that.setData({
        urla:res.data,
      })
      that.xiazai();
    })
  },
  xiazai(){
    var that = this;
      wx.showLoading({
        title: '正在下载...',
      })
      
      // 下载 PDF 文件到本地
      wx.downloadFile({
        url: that.data.urla,
        success: function (res) {
          console.log("下载成功")
          console.log(res)
          const filePath = res.tempFilePath
      
          // 打开本地 PDF 文件进行预览
          wx.openDocument({
            filePath: filePath,
            fileType: 'pdf',
            success: function () {
              console.log('打开文档成功')
            },
            fail: function (error) {
              console.log('打开文档失败', error)
            },
            complete: function () {
              wx.hideLoading()
            }
          })
        },
        fail: function (error) {
          console.log('下载文件失败', error)
          wx.hideLoading()
      
          // 提示用户下载失败信息
          wx.showToast({
            title: '下载失败，请稍候再试！',
            icon: 'none'
          })
        }
      })
  },
  loadStuDetail(){
    //getStuDetailForIdUrl
    var that = this
    util.request(api.getStuDetailForIdUrl, {id:this.data.id,key:api.key}).then(function (res) {
      //console.log(JSON.stringify(res.data));
      if(res.errno === 402){
        wx.showModal({
          title: '错误',
          content:'不被允许的请求',
          showCancel: false
        })
        return;
    }
      that.setData({
        stu:res.data
      })
      that.loadHtData(res.data.classTypeId);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  changeMoneyToChinese(money){  
    var cnNums = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"); //汉字的数字  
    var cnIntRadice = new Array("","拾","佰","仟"); //基本单位  
    var cnIntUnits = new Array("","万","亿","兆"); //对应整数部分扩展单位  
    var cnDecUnits = new Array("角","分","毫","厘"); //对应小数部分单位  
    //var cnInteger = "整"; //整数金额时后面跟的字符  
    var cnIntLast = "元"; //整型完以后的单位  
    var maxNum = 999999999999999.9999; //最大处理的数字  
      
    var IntegerNum; //金额整数部分  
    var DecimalNum; //金额小数部分  
    var ChineseStr=""; //输出的中文金额字符串  
    var parts; //分离金额后用的数组，预定义  
    if( money == "" ){  
        return "";  
    }  
    money = parseFloat(money);  
    if( money >= maxNum ){  
        $.alert('超出最大处理数字');  
        return "";  
    }  
    if( money == 0 ){  
        //ChineseStr = cnNums[0]+cnIntLast+cnInteger;  
        ChineseStr = cnNums[0]+cnIntLast  
        //document.getElementById("show").value=ChineseStr;  
        return ChineseStr;  
    }  
    money = money.toString(); //转换为字符串  
    if( money.indexOf(".") == -1 ){  
        IntegerNum = money;  
        DecimalNum = '';  
    }else{  
        parts = money.split(".");  
        IntegerNum = parts[0];  
        DecimalNum = parts[1].substr(0,4);  
    }  
    if( parseInt(IntegerNum,10) > 0 ){//获取整型部分转换  
        var zeroCount = 0;  
        var IntLen = IntegerNum.length;  
        for(var i=0;i<IntLen;i++ ){  
            var n = IntegerNum.substr(i,1);  
           var p = IntLen - i - 1;  
            var q = p / 4;  
           var m = p % 4;  
            if( n == "0" ){  
                zeroCount++;  
            }else{  
                if( zeroCount > 0 ){  
                    ChineseStr += cnNums[0];  
                }  
                zeroCount = 0; //归零  
                ChineseStr += cnNums[parseInt(n)]+cnIntRadice[m];  
            }  
            if( m==0 && zeroCount<4 ){  
                ChineseStr += cnIntUnits[q];  
            }  
        }  
        ChineseStr += cnIntLast;  
        //整型部分处理完毕  
    }  
    if( DecimalNum!= '' ){//小数部分  
        decLen = DecimalNum.length;  
        for( i=0; i<decLen; i++ ){  
            n = DecimalNum.substr(i,1);  
            if( n != '0' ){  
                ChineseStr += cnNums[Number(n)]+cnDecUnits[i];  
            }  
        }  
    }  
    if( ChineseStr == '' ){  
        //ChineseStr += cnNums[0]+cnIntLast+cnInteger;  
        ChineseStr += cnNums[0]+cnIntLast;  
    }/* else if( DecimalNum == '' ){ 
        ChineseStr += cnInteger; 
        ChineseStr += cnInteger; 
    } */  
    return ChineseStr;  
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  loadHtData(classId){
    var that = this
    var userid = wx.getStorageSync("userid");
    //var classId = this.data.classTypeId;
    util.request(api.queryHtByUserIdAndClassIdUrl, {userId:userid,classId:classId}).then(function (res) {
      //console.log(JSON.stringify(res));
      var stu = that.data.stu;//res.data.stu;
      var classtype = res.data.class;
      var dept = res.data.dept;
      var ht = res.data.ht;
      var num = res.data.num;
      that.setData({
        num:num
      })

      var sex = '女';
      if(stu.gender == '1'){
        sex = '男';
      }
      var dx = that.changeMoneyToChinese(parseInt(classtype.price));


      if(typeof(res.data.ht) == 'undefined'){
        that.setData({
          showModal:true,
          dzht:false,
          xbflag:false,
          'htData.name':stu.name,
          'htData.sex':sex,
          'htData.cardNo':stu.cardNo,
          'htData.tel':stu.mobile,
          'htData.address':stu.address,
          'htData.trainModel':classtype.trainModel,
          'htData.schoolName':dept.name,
          'htData.schoolCardNo':dept.licenseNo,
          'htData.schoolFddbr':dept.legalPerson,
          'htData.schoolTel':dept.phone,
          'htData.schoolAddress':dept.address,
          'htData.price':classtype.price,
          'htData.dx':dx,
          'htData.subject2Price':'0',
          'htData.subject3Price':'0',
          'htData.serviceaddress':'0',
          'htData.servicewww':'0',
          'htData.servicesite':'0',
          'htData.serviceroute':'0',
          'htData.jcMoney':'0',
          'htData.lcMoney':'0',
          'htData.day':'0',
          'htData.subjecttwo':'0',
          'htData.subjectthree':'0',
          'htData.tfJcMoney':'0',
          'htData.tfGlJcMoney':'0'
        })


      }else{
     
        that.setData({
          showModal:true,
          dzht:false,
          xbflag:false,
          'htData.name':stu.name,
          'htData.sex':sex,
          'htData.cardNo':stu.cardNo,
          'htData.tel':stu.mobile,
          'htData.address':stu.address,
          'htData.trainModel':classtype.trainModel,
          'htData.schoolName':dept.name,
          'htData.schoolCardNo':dept.licenseNo,
          'htData.schoolFddbr':dept.legalPerson,
          'htData.schoolTel':dept.phone,
          'htData.schoolAddress':dept.address,
          'htData.price':classtype.price,
          'htData.dx':dx,
          'htData.subject2Price':ht.kmtwo,
          'htData.subject3Price':ht.kmthree,
          'htData.serviceaddress':ht.serviceaddress,
          'htData.servicewww':ht.servicewww,
          'htData.servicesite':ht.servicesite,
          'htData.serviceroute':ht.serviceroute,
          'htData.jcMoney':ht.jcMoney,
          'htData.lcMoney':ht.lcMoney,
          'htData.day':ht.day,
          'htData.subjecttwo':ht.subjecttwo,
          'htData.subjectthree':ht.subjectthree,
          'htData.tfJcMoney':ht.tfJcMoney,
          'htData.tfGlJcMoney':ht.tfGlJcMoney,
        })
      }

    })
  }
})